package com.foreknow.view;
import com.foreknow.bean.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class SwingDemo extends JFrame  {

    public SwingDemo() {
        // 创建 JFrame 实例
        //JFrame frame = new JFrame("Swing Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);

        // 创建 JPanel
        JPanel panel = new JPanel();
        // 使用边界布局
        panel.setLayout(new BorderLayout());

        GuestbookService service = new GuestbookServiceImpl();
        List<Object> list = service.queryAll(); //调用Service层方法查询所有留言信息
        // 创建表格数据和 JTable
        String[] columnNames = {"id", "name", "phone","email","title","content","createdtime"};
        //        Object[][] data = {
        //                {"Data 1", "Data 2", "Data 3","Data 4","Data 5","Data 6","Data 7"},
        //                {"Data 8", "Data 9", "Data 10","Data 11","Data 12","Data 13","Data 14"}
        //        };
        Object[][] data = new Object[list.size()][7];
        for(int i = 0;i<list.size();i++) {
            Guestbook gb = (Guestbook) list.get(i);
            data[i][0] = gb.getId();
            data[i][1] = gb.getName();
            data[i][2] = gb.getPhone();
            data[i][3] = gb.getEmail();
            data[i][4] = gb.getTitle();
            data[i][5] = gb.getContent();
            data[i][6] = gb.getCreatedtime();
        }
        JTable table = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 创建四个按钮
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton btn_add = new JButton("add");
        btn_add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("add operation......");
                //跳转页面,需要在AddGuestbook()构造方法中设置可见性
                AddGuestbook addGuestbook = new AddGuestbook();
                SwingDemo.this.dispose(); //隐藏当前窗口
            }
        });
        buttonPanel.add(btn_add);
        buttonPanel.add(new JButton("Button 2"));
        buttonPanel.add(new JButton("Button 3"));
        buttonPanel.add(new JButton("Button 4"));
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 创建搜索框
        JTextField searchField = new JTextField(20);
        panel.add(searchField, BorderLayout.NORTH);

        // 将 panel 添加到 frame
        add(panel);

        // 显示窗口
        setVisible(true);
    }
    public static void main(String[] args) {
       new SwingDemo();
    }
}
